package com.bra.ui.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bra.R;
import com.bra.bean.CommentBean;
import com.bra.bean.ArticleBean;
import com.bra.request.UrlConstants;
import com.bra.ui.adapter.Comment_adapter;
import com.bra.ui.adapter.ArticleList_adapter;
import com.bra.ui.base.BaseActivity;
import com.bra.utils.CommonUtils;
import com.bra.utils.DataCleanManager;
import com.bra.utils.SPHelper;
import com.bra.utils.StringHelper;
import com.bra.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * 资讯详情页
 * 
 * @author lenovo
 *
 */
public class ArticleDetailsActivity extends BaseActivity {
	private ImageView activity_back,activity_shoucang;
	private TextView activity_title,zxxq_submit;	
    private WebView webview_xq;
    private String ZixunxqUrl = UrlConstants.IP;
	private RequestQueue mRequestQueue;
    private String url="http://auto.news18a.com/m/price/index/index/gwifi/";
    private  Bundle bundle;
    private String id;
    private ListView zx_pinglun_list;
    private Comment_adapter adapter;
    private String[] pinglunitems = new String[4];
	private LinearLayout ZXxq_title;
	private Boolean Is_Login;
	private String userid,token;
	private EditText zxxq_et;
	private CommentBean commnemt;
	private List<CommentBean>commnemts;
	@Override
	protected View onCreateView(LayoutInflater inflater,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.activity_articledetails, null);
	}

	@Override
	protected void onViewCreated(Bundle savedInstanceState) {
		mRequestQueue = Volley.newRequestQueue(this);
		Is_Login=SPHelper.readBoolean(ArticleDetailsActivity.this, "Is_Login", false);
		activity_title = (TextView) findViewById(R.id.activity_title);
		activity_back = (ImageView) findViewById(R.id.activity_back);
		activity_title.setText("资讯详情");
		ZXxq_title = (LinearLayout) findViewById(R.id.cgxq_title);
		ZXxq_title.setVisibility(View.VISIBLE);
		activity_shoucang = (ImageView) findViewById(R.id.activity_shoucang);
		webview_xq=(WebView) findViewById(R.id.webview_xq);
		zxxq_submit=(TextView) findViewById(R.id.zxxq_submit);
		zxxq_et=(EditText) findViewById(R.id.zxxq_et);
		zx_pinglun_list=(ListView) findViewById(R.id.zx_pinglun_list);
		init();
		 bundle = getIntent().getExtras();
		 id=bundle.getString("id", "");
	 /*if (adapter == null) {
			 adapter = new Comment_adapter(ZiXunXqActivity.this,commnemts);
			}
		 zx_pinglun_list.setAdapter(adapter);
		*/ 
		 httpRequestZxxqInfo(ArticleDetailsActivity.this,ZixunxqUrl,RequestParams());		
		 httpRequestPL_ListInfo(ArticleDetailsActivity.this,ZixunxqUrl);
	}
	private  void init(){		
	        //设置WebView属性，能够执行Javascript脚本  
		webview_xq.getSettings().setJavaScriptEnabled(true);  
	        //加载需要显示的网页  
		webview_xq.loadUrl(url);  
	        //设置Web视图  
		webview_xq.setWebViewClient(new HelloWebViewClient ());  
	}
	//Web视图  
    private class HelloWebViewClient extends WebViewClient {  
        @Override 
        public boolean shouldOverrideUrlLoading(WebView view, String url) {  
            view.loadUrl(url);  
            return true;  
        }  
    }  
	@Override
	protected void setListener() {
		activity_back.setOnClickListener(click);
		zxxq_submit.setOnClickListener(click);
		
	}

	private View.OnClickListener click = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.activity_back:
				finish();
				break;
			case R.id.activity_shoucang:
				finish();
				break;
			case R.id.zxxq_submit:
			String 	et_text=zxxq_et.getText().toString().trim();
			 if(!Is_Login){
				  Toast.makeText(ArticleDetailsActivity.this, "去登录"+Is_Login, 0).show();
				  goActivity(LoginActivity.class);
			  }else{
					userid=SPHelper.readString(ArticleDetailsActivity.this, "userId");
					token=SPHelper.readString(ArticleDetailsActivity.this, "token");
					httpRequestZx_PLInfo(ArticleDetailsActivity.this,ZixunxqUrl,Request_PL_Params(userid,token,et_text));
			  }
				break;
			default:
				break;
			}

		}
	};
	//资讯详情我网络请求
	private void httpRequestZxxqInfo(Context context, String url,
			final HashMap<String, String> params) {
		StringRequest req = new StringRequest(Request.Method.POST, url,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						try {		
				//	    System.out.println(response.toString());						
								
							return;
						} catch (Exception e) {
							e.printStackTrace();
						}
						Toast.makeText(ArticleDetailsActivity.this, "数据异常，请检查网络", 0)
								.show();
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError volleyError) {
						Toast.makeText(ArticleDetailsActivity.this, "访问失败，请检查网络", 0)
								.show();
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> map = params;
				return map;
			}
		};
		mRequestQueue.add(req);
	}

	private HashMap<String, String> RequestParams() {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("userId", "");
		map.put("equipment", "android");
		map.put("requestType", "View_Article_Api");
		map.put("token", "");
		map.put("id", id);					
		return map;
	}
	//对资讯进行评论的接口请求及参数
	private void httpRequestZx_PLInfo(Context context, String url,
			final HashMap<String, String> params) {
		StringRequest req = new StringRequest(Request.Method.POST, url,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						try {		
					     System.out.println(response.toString());					   
					
							return;
						} catch (Exception e) {
							e.printStackTrace();
						}
						Toast.makeText(ArticleDetailsActivity.this, "数据异常，请检查网络", 0)
								.show();
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError volleyError) {
						Toast.makeText(ArticleDetailsActivity.this, "访问失败，请检查网络", 0).show();
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> map = params;
				return map;
			}
		};
		mRequestQueue.add(req);
	}

	private HashMap<String, String> Request_PL_Params(String userid,String token,String content) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("userId", userid);
		map.put("equipment", "android");
		map.put("requestType", "Comment_Api");
		map.put("token", token);
		map.put("content", content);
		map.put("contentId", id);
		map.put("modelKey", "article");
		return map;
	}
	//获取评论列表接口网络
	private void httpRequestPL_ListInfo(Context context, String url) {		
		
		 AsyncHttpClient client = new AsyncHttpClient();  	     
      // 创建请求参数  
	        RequestParams params = new RequestParams();  	        
	        params.put("userId", "");
	        params.put("equipment", "android");
	        params.put("requestType", "List_Comment_Api");
	        params.put("token", ""); 	       
	        
	        // 执行post方法  
	        client.post(url, params, new JsonHttpResponseHandler(){

				@Override
				public void onFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONObject errorResponse) {
					// TODO Auto-generated method stub
					super.onFailure(statusCode, headers, throwable, errorResponse);
					Toast.makeText(ArticleDetailsActivity.this, "网络错误", 0).show();
				}

				@Override
				public void onSuccess(int statusCode, Header[] headers,
						JSONObject response) {
					// TODO Auto-generated method stub
					super.onSuccess(statusCode, headers, response);
			//		System.out.println(response.toString()+"====");
					commnemts=new ArrayList<CommentBean>();
					try {
						JSONObject comment=new JSONObject(response.toString());
					    JSONArray array	=comment.getJSONArray("commentList");
					    for(int i=0;i<array.length();i++){
					    	JSONObject object =array.getJSONObject(i);
					    	String content=object.getString("content");
					    	String username=object.getString("username");
					    	String createDate=object.getString("createDate");					    	
					    	String imgSrc=object.getString("imgSrc");
					    	commnemt=new CommentBean(content,username,createDate,imgSrc);
					    	commnemts.add(commnemt);
					    }
					    if (adapter == null) {
							 adapter = new Comment_adapter(ArticleDetailsActivity.this,commnemts);
							}
						 zx_pinglun_list.setAdapter(adapter);			
						return;
					} catch (JSONException e) {
						
						e.printStackTrace();
					}
					Toast.makeText(ArticleDetailsActivity.this, "数据异常，请检查网络", 0).show();					
				}
	        	
	        });  
	}
}